<?php

class comite extends CI_Controller {
	var $titp='Comites';
	var $url ='comite/';

	function index(){
		redirect($this->url.'filteredgrid');
	}

	function filteredgrid(){
		$this->load->library('rapyd');

		$filter = new datafilter_library();
		$filter->label = 'Buscar Comité';
		$filter->db->from('comite');

		$filter->field('input','nombre'  ,'Nombre')
			->attributes(array('style' => 'width:170px'));

		$filter->buttons('reset', 'search');
		$filter->build();

		$grid = new datagrid_library();
		$grid->label = 'Lista de comites ';
		$grid->per_page = 40;
		$grid->source($filter);

		$grid->column('nombre','Comité',true)
                        ->url('comite/dataedit/show/{id}');
                
		$grid->column('creacion','Fecha de Creación',true)
			->attributes(array('align'=>'center'));
			//->callback('iso2human',rpd_date_helper::);

		$link=anchor_popup('comite/formatos/{id}','Imprimir',array());
		$grid->column($link ,'Imprimir' ,true)
			->attributes(array('align'=>'right'));

		// que hace esta linea
                $grid->back_url = site_url($this->url.'mision');
                //boton crear
		$grid->add_button(array('url'=>$this->url.'dataedit/create'));
                // ?
		$action = "javascript:window.location.href='".site_url('/')."'";
                //boton regresar
		$grid->button('btn_reg', 'Regresar', $action, 'TR');
                //?
		$grid->buttons('modify','save','undo','delete','back');
                //construye la vista
		$grid->build();
		//--echo rpd_date_helper::iso2human("2001-01-01");
		$data['content'] =  $filter->output.$grid->output;
		$data['head']    = $this->rapyd->head().script('jquery.js');
                // coloca un titulo en la cabecera de la pagina
		$data['title']   = '';
                // construye la vista
		$this->load->view('view_ventanas_sola', $data);
	}

	function db2human($date){
		return $date;
		//return rpd_date_helper::iso2human($date);
	}


	function dataedit(){
		$this->load->library('rapyd');

		$edit = new dataedit_library();
		$edit->label = 'Comite';
                // ?
		$edit->back_url = site_url($this->url.'filteredgrid');
                
                //Busca la base de datos
		$edit->source('comite');
                //?
		$edit->pre_process(array('delete'), array($this, 'pre_delete'));
                // Se inserta el nombre: sin espacios en blanco al principio, unico y obligatorio
		$edit->field('input','nombre','Nombre')
			->rule('trim|unique|required');
                // Se inserta la fecha de cracion
		$edit->field('date','creacion','Fecha de creacion')
			->attributes(array('style'=>'width: 125px'))
			->set_insert_value(date('Y-m-d'));

		$edit->field('dropdown','razon','Sector')
			->options(array(
				''  =>'Seleccionar',
				'E' =>'Escolar',
				'C' =>'Comunidad',
				'I' =>'Institucional'))
			->rule('required');

		$edit->field('dropdown','id_municipio','Municipio')
			->rule('required')
			->option('','Seleccionar')
			->options('SELECT id,nombre FROM municipios ORDER BY nombre')
			->attributes(array('style'=>'width: 200px'));
		
		$edit->field('dropdown','id_tban','Banco')
			->rule('required')
			->option('','Seleccionar')
			->options('SELECT id,nombre FROM tban ORDER BY nombre')
			->attributes(array('style'=>'width: 200px'));		

		$edit->field('input','cuenta','Numero de cuenta')
			->rule('trim|unique|required');
	
		$edit->field('container','integrantes','integrantes');
		
		$edit->buttons('modify','save','undo','delete','back');
		$edit->build();

		if ($this->rapyd->uri->value('show')){//?
                        //?
			if ($this->rapyd->uri->value('show1|modify1|update1|create1|insert1|do_delete1')){
                            // llamada a la funcion integrante() para crear un nuevo integrante
				$edit->nest('integrantes',$this->integrante());
			}else {
                            // llamada a la funcion integrante() para listar los integrantes
				$edit->nest('integrantes',$this->integrantes());
			}
	}

		$data['head']    = $this->rapyd->head();
		$data['head']    = script('jquery.js').$this->rapyd->head();
		$data['title']   = '<h1>Ficha de Comites</h1>';
		$data['content'] = $edit;
		$this->load->view('view_ventanas_sola', $data);
	}

	function integrantes(){

		$grid = new datagrid_library();
		$grid->label = 'Lista de integrantes';
		$grid->source('integrantes');
                // muestra los integrantes del comite seleccionado
		$grid->db->where('id_comite',$this->rapyd->uri->value('create|show|modify|update'));
		// los ordena por nombre
		$grid->db->orderby('nombre');
		// imprimir nombre de integrante, pero no permite modificar
		$grid->column('nombre'  , 'Nombre'  ,true);
			//->url($this->url.'dataedit/show/{id_comite}/modifi1/{id}');
		$grid->column('apellido', 'Apellido',true);
		$grid->column('cedula'  , 'Cédula'  ,true);

		//if integrnates!=null
		$grid->column('Modificar', '&nbsp;')
			->url($this->url.'dataedit/show/{id_comite}/modifi1/{id}');
		$grid->column('Eliminar', '&nbsp;')
			->url($this->url.'dataedit/show/{id_comite}/do_delete1/{id}');
		$grid->buttons('add');

		//$grid->add_button(array('url'=>$this->url.'dataedit/create'));
		$grid->build();

		return $grid->output;
	}


	public function integrante(){
		$this->load->library('rapyd');

		$edit = new dataedit_library();
		$edit->label = 'Integrantes';
		$edit->back_url = site_url($this->url.'dataedit/show/'.$this->rapyd->uri->value('show'));
		$edit->back_save = true;
		$edit->back_delete = true;
		$edit->back_cancel = true;
		$edit->back_cancel_save = true;
		$edit->source('integrantes');
		$edit->pre_process(array('insert'), array($this, 'pre_integrante_insert'));
                //$edit->pre_process(array('insert'), array($this, 'pre_integrante_insert'));

		$edit->field('input','nombre'  ,'Nombre')
			->attributes(array('style' => 'width:170px'))
			->rule('trim|required|ucfirst');

		$edit->field('input','apellido','Apellido')
			->attributes(array('style' => 'width:170px'))
			->rule('trim|required|ucfirst');

		$edit->field('input','cedula'  ,'Cédula'  )
			->attributes(array('style' => 'width:170px'))
			->rule('trim|unique|required');

		$edit->field('dropdown','sexo','Sexo')
			->options(array(
				'' =>'Seleccionar',
				'F'=>'Femenino',
				'M'=>'Masculino'))
			->rule('required');

		$edit->field('input','telefono'  ,'Teléfono')
			->attributes(array('style' => 'width:170px'));

		$edit->field('dropdown','cargo'  ,'Cargo')
			->options(array(
				'C'=>'Coordinador',
				'M'=>'Miembro'))
			->attributes(array('style' => 'width:170px'));

		$edit->field('textarea', 'direccion','Dirección' );

		$edit->field('hidden','id_comite','')->insert_value($this->rapyd->uri->value('show'));

		$edit->buttons('modify','save','undo','back');
		$edit->build();

		return $edit->output;
	}

		
	function pre_integrante_insert($model){
		$cedula = $model->get('cedula');
                $cargo = $model->get('cargo');

		$this->db->select(array('b.nombre'));
		$this->db->from('integrantes AS a');
		$this->db->join('comite AS b','a.id_comite=b.id');
		$this->db->where('a.cedula',$cedula,'a.cargo',$cargo);

		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$row   = $query->row();
			$comite= $row->nombre;
                        $cargo = $row->cargo;
			$model->error_string = '--El integrante que esta tratando de insertar ya fue registrado para el comité '.$comite.'.';
			return false;
		}else{
			return true;
		}
	}

	function pre_delete($model){
		$id = $model->get('id');

		$this->db->from('integrantes');
		$this->db->where('id_comite',$id);
		$cana = $this->db->count_all_results();

		if($cana==0){
			return true;
		}
		$model->error_string = '--No se puede eliminar una zona con cuencas relacionas.';
		return false;
	}

	function formatos($id){
		$this->load->helper('date');
		$this->db->select(array('a.*','b.nombre AS muni'));
		$this->db->from('comite AS a');	
		$this->db->join('municipios AS b','a.id_municipio=b.id');
		$this->db->where('a.id',$id);
		$query = $this->db->get();

		$data = array();
		if ($query->num_rows() > 0){
			$row  = $query->row();
			$data['nombre'] = $row->nombre;
			$data['municipio'] = $row->muni;
			$data['cuenta'] = $row->cuenta;
			$data['saldo'] = $row->saldo;
			
		}
	
		$this->db->select(array('a.*','c.nombre AS especie','b.cantidad AS cant'));
		$this->db->from('proyectos AS a');
		$this->db->join('cultivos AS b','a.id=b.id_proyecto');
		$this->db->join('especiesp AS c','c.id=b.id_especiesp');
		$this->db->where('a.id_comite',$id);	
		$query = $this->db->get();
		$data['cantidad'] =$query->result();
		
		$this->db->select('SUM(a.hectareas_recu) AS recuperado');
		$this->db->from('proyectos AS a');
		$this->db->where('id_comite',$id);
		$query = $this->db->get();
		$aux2  = $query->row();
		$data['recu'] = $aux2->recuperado;

		$this->load->view('formatos/nplantas_por zonas.php', $data);
	}

}
